package com.ifnk.portaljava.hlyt.dao.impl;

import com.ifnk.portaljava.dapWeb.advance.DBAccess;
import com.ifnk.portaljava.hlyt.beans.UserAllowedIp;
import com.ifnk.portaljava.hlyt.dao.IUserAllowedJdbcDao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserAllowedIpJdbcDaoImpl implements IUserAllowedJdbcDao {

	public void save(UserAllowedIp allowedIp,int userId, Connection conn) {
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int id = 0;
		try {
			String idSql = "select max(id) as maxId from user_allowed_ip";
			stmt = conn.createStatement();
			rs = stmt.executeQuery(idSql);
			while (rs.next()) {
				id = rs.getInt("maxId") + 1;
			}
			String sql = "insert into user_allowed_ip(id,ip,user_id) values(?,?,?)";
			System.out.println("insert sql:" + sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
			pstmt.setString(2, allowedIp.getIp());
			pstmt.setInt(3, userId);
			pstmt.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (rs != null) {
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void deleteByUserId(int userId, Connection conn) {
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			String sql = "delete from user_allowed_ip where user_id="
					+ userId;
			System.out.println("sql:" + sql);
			stmt.execute(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

	public List<UserAllowedIp> findByUserid(int userId) {
		DBAccess db = new DBAccess();
		ResultSet rs = null;
		List<UserAllowedIp> ipList = new ArrayList<UserAllowedIp>();
		try {
			String sql = "select id,ip from user_allowed_ip where user_id="+userId;
			System.out.println("sql:" + sql);
			rs = db.queryTable(sql);
			UserAllowedIp ip = null;
			while (rs.next()) {
				ip = new UserAllowedIp();
				ip.setId(rs.getInt("id"));
				ip.setIp(rs.getString("ip"));
				ipList.add(ip);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return ipList;
	}

}
